package src.main.beiwanglu;

import java.util.ArrayList;
import java.util.List;

public class MementoPatternDemo {
    public static void main(String[] args) {
        Originator originator = new Originator();
        CareTaker careTaker = new CareTaker();
        originator.setState("状态 #1");
        originator.setState("状态 #2");
        careTaker.add(originator.saveStateToMemento()); //将状态存储到备忘录类
        originator.setState("状态 #3");
        careTaker.add(originator.saveStateToMemento());
        originator.setState("状态 #4");
        //获取备忘录存储状态
        System.out.println("Current State: " + originator.getState());
        originator.getStateFromMemento(careTaker.get(1));
        System.out.println("First saved State: " + originator.getState());
        originator.getStateFromMemento(careTaker.get(0));
        System.out.println("Second saved State: " + originator.getState());
        //-------------------------------------------



    }
}
class Memento { //备忘录类，数据类。对象作为存储节点信息。
    private String state;

    public Memento(String state){
        this.state = state;
    }

    public String getState(){
        return state;
    }
}
class Originator {
    private String state;

    public void setState(String state){
        this.state = state;
    }

    public String getState(){
        return state;
    }

    public Memento saveStateToMemento(){
        return new Memento(state);
    }

    public void getStateFromMemento(Memento Memento){
        state = Memento.getState();
    }
}
class CareTaker {  //管理备忘录类，存储不同节点状态
    private List<Memento> mementoList = new ArrayList<Memento>();

    public void add(Memento state){
        mementoList.add(state);
    }

    public Memento get(int index){
        return mementoList.get(index);
    }
}